package com.forotuxpan.appforotuxpan;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.os.AsyncTask;
import android.os.Build;
import android.os.StrictMode;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.util.ArrayList;
import com.forotuxpan.appforotuxpan.R;


public class EmpresasActivity extends AbstractListViewEmpresaActivity /*BaseActionBarActivity*/ {

    String letra = "A";
    Activity activity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_empresas);

        activity = this;

        datasource = DatasourceEmpresa.getInstance();
        ActionBar actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);

        Bundle bundle = getIntent().getExtras();
        letra = bundle.getString("Letra");
        actionBar.setTitle(getResources().getString(R.string.title_activity_empresas) + "(" + letra + ")");

        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        if (isOnline()) {
            GetEmpresasPorLetra();
        }
        else
        {
            Toast.makeText(this, getResources().getString(R.string.msg_no_conexion), Toast.LENGTH_SHORT).show();
        }
        /*
        ListView lstListado = (ListView)findViewById(R.id.LstEmpresas);
        lstListado.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    Intent i = new Intent(view.getContext(), EmpresaDetalleActivity.class);
                    i.putExtra("Nombre", ((Empresa) parent.getItemAtPosition(position)).getNombre());
                    i.putExtra("Logotipo", ((Empresa) parent.getItemAtPosition(position)).getLogotipo());
                    i.putExtra("Telefono", ((Empresa) parent.getItemAtPosition(position)).getTelefono());
                    i.putExtra("Email", ((Empresa) parent.getItemAtPosition(position)).getEmail());
                    i.putExtra("Direccion", ((Empresa) parent.getItemAtPosition(position)).getDireccion());
                    startActivity(i);
                    //Toast.makeText(getBaseContext(), "Pendiente Activity", Toast.LENGTH_SHORT).show();
                } catch (Exception e) {
                    Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });
        */

        getListView().setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView arg0, int arg1) {
                // nothing here
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if (load(firstVisibleItem, visibleItemCount, totalItemCount)) {
                    loading = true;
                    getListView().addFooterView(footerView, null, false);
                    (new AbstractListViewEmpresaActivity.LoadNextPage()).execute("");
                }
            }
        });
    }

    public void GetEmpresasPorLetra() {
        task = new AsyncTask<Void, Void, Void>() {
            ArrayList empresas;
            boolean isErrorConnec = false;
            @Override
            protected void onPreExecute() {
                showLoading(activity);
            }

            @Override
            protected Void doInBackground(Void... arg0) {
                try {
                    empresas = FromJSONtoArrayList_Proveedores(isErrorConnec);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (isErrorConnec) {
                                Toast.makeText(getBaseContext(), getResources().getString(R.string.msg_problema_conexion), Toast.LENGTH_SHORT).show();
                            } else {
                                //ListView listView1 = (ListView) findViewById(R.id.LstEmpresas);
                                //listView1.setAdapter(new ItemAdapterEmpresas(listView1.getContext(), empresas));
                                datasource = DatasourceEmpresa.getInstance(empresas);
                                footerView = ((LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer, null, false);
                                getListView().addFooterView(footerView, null, false);
                                setListAdapter(new CustomArrayAdapterEmpresa(activity, datasource.getData(0, PAGESIZE)));
                                getListView().removeFooterView(footerView);
                            }
                        }
                    });
                }
                /*catch (InterruptedException e) {
                    //e.printStackTrace();
                    mCallbacks.hiddenCargando();
                }*/
                catch (Exception ex) {
                    hiddenLoading();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                hiddenLoading();
            }

        };
        //task.execute((Void[])null);
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
            task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        else
            task.execute((Void[]) null);
    }

    public ArrayList FromJSONtoArrayList_Proveedores(boolean isErrorConnec) {
        ArrayList listItems = new ArrayList();

        try {

            // Replace it with your own WCF service path
            URL json = new URL("http://serviciosandroid.forotuxpan.com/wsAndroid/get_listado_empresas_por_letra.php?pLetra=" + letra);
            URLConnection jc = json.openConnection();
            BufferedReader reader = new BufferedReader(new InputStreamReader(jc.getInputStream()));

            String line = reader.readLine();

            JSONObject jsonResponse = new JSONObject(line);
            JSONArray jsonArray = jsonResponse.getJSONArray("Empresas");

            for (int i = 0; i < jsonArray.length(); i++) {

                JSONObject jObject = (JSONObject)jsonArray.get(i);
                // "FullName" is the property of .NET object spGetPersonsResult,
                // and also the name of column in SQL Server 2008

                String pathImg = jObject.getString("Logotipo");
                if(pathImg==null || pathImg=="")
                    pathImg = "http://forotuxpan.com/images/logo_forotuxpan.gif";
                else
                    pathImg = "http://forotuxpan.com/logotipos/" + pathImg;
                URL imageUrl = null;
                Bitmap img = null;
                HttpURLConnection conn = null;
                try {
                    imageUrl = new URL(pathImg);
                    conn = (HttpURLConnection) imageUrl.openConnection();
                    conn.connect();

                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inSampleSize = 2; // el factor de escala a minimizar la imagen, siempre es potencia de 2

                    img = BitmapFactory.decodeStream(conn.getInputStream(), new Rect(0, 0, 0, 0), options);

                }
                catch (IOException e) {
                    e.printStackTrace();

                }

                listItems.add(new Empresa(jObject.getInt("Id"), URLDecoder.decode(jObject.getString("Nombre"), "UTF-8"), URLDecoder.decode(jObject.getString("Categoria"), "UTF-8"), img, jObject.getString("Logotipo"), jObject.getString("Telefono"), URLDecoder.decode(jObject.getString("Email"), "UTF-8"), URLDecoder.decode(jObject.getString("Direccion"), "UTF-8") ));
            }

            reader.close();

        }catch(Exception e){
            //Toast.makeText(getActivity(), e.toString(), Toast.LENGTH_LONG).show();
            //Toast.makeText(getActivity(), "Servicio no disponible, intente mas tarde.", Toast.LENGTH_LONG).show();
            isErrorConnec = true;
            Log.d("Error Empresas:", e.getMessage());
        }

        return listItems;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.home || id == 16908332 ) {
            this.finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_empresas, menu);
        return true;
    }

}
